<script lang="ts" setup>
import { getEnterpriseListAPI } from '@/apis/card';
import { updateEnterpriseDetailAPI, uploadAPI } from '@/apis/common';
import { createRentAPI, delEnterpriseAPI, delRentAPI, getRentBuildListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
import type { Datum, DatuRentBuilding, Enterprise, EnterpriseListParams, RentParams } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRequestOptions } from 'element-plus';
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';

// 前端自定义类型 
interface  EnterpriseWithRent  extends  Enterprise{
      // 合同列表
      rentList: Datum[]
}

    const params=ref<EnterpriseListParams>({
        page:1,
        pageSize:5,
        name:'',     
    })

    const list=ref<EnterpriseWithRent[]>([])
    const total=ref(0)
    const  getLiat=async()=>{ 
      const res=await getEnterpriseListAPI(params.value)
      // console.log(res);
      list.value=res.data.rows.map(item=>({
        ...item,
        rentList:[]
      }))
      total.value=res.data.total
    }

    getLiat()
    // 搜索功能
    const onSearch=()=>{
      params.value.page=1
      getLiat()
    }

    // -----------------
       // 编辑
       const  fetchEnterpriseDetail=async()=>{
    const res=await updateEnterpriseDetailAPI(route.params.id as string)
    // console.log(res);
    }
    // 判断router是否有id
    const route=useRoute()
      if(route.params.id){
        fetchEnterpriseDetail()
      }

    // 删除企业
    const delExterprise=(id:number)=>{
           ElMessageBox.confirm('确定删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async() => {
              await delEnterpriseAPI(id)
              ElMessage({
                type: 'success',
                message: '删除成功!',
              })
              getLiat()
            })
           
    }

    // --------------------------
    // 添加合同
    const dialogVisible=ref(false)
// 添加基本数据
const rentForm=ref<RentParams>({
     buildingId:undefined,
     startTime:'',
     endTime:'',
     contractUrl:'',
     contractId:0,
     type:0,
     enterpriseId:0
})

const  rentRules=ref<FormRules<RentParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁日期', trigger: 'change' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]

})
// 可租赁楼宇列表
const  buildList =ref<DatuRentBuilding[]>([])
// 显示弹窗
    const addRent = async(id:number)=>{
      dialogVisible.value=true
    //  获取可租赁楼宇列表
    const res=await getRentBuildListAPI()
    // console.log(res);
    buildList.value=res.data

     // 保存企业id，用于添加合同
  rentForm.value.enterpriseId=id
    

    }

   //  添加完成-关闭弹窗
    const closeRent=()=>{
      dialogVisible.value=false
      // 重置表单校验前端
      addFormRef.value?.resetFields()
      // 特殊清空数组表单
      timeArr.value=[]
      rentForm.value={
        buildingId:undefined,
     startTime:'',
     endTime:'',
     contractUrl:'',
     contractId:0,
     type:0,
     enterpriseId:0
      }
     
    }
// 禁用之前时间
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now()
}
// 世间选择器-监听时间变化
const timeArr=ref<string[]>([])
watch(timeArr,(val)=>{
  if(val){
    rentForm.value.startTime=val[0]
    rentForm.value.endTime=val[1]
  }else{
    rentForm.value.startTime=''
    rentForm.value.endTime=''
  }
},{ deep:true })

const addFormRef = ref<FormInstance>()
// 上传租赁合同
const onUploadRequest = async(options: UploadRequestOptions)=>{
  const fd =new FormData()
  fd.append('file' ,options.file)
  fd.append('type','contract')
  // 调用接口上传
  const res=await uploadAPI(fd)
  // 保存合id url
  rentForm.value.contractUrl=res.data.url
  rentForm.value.contractId=res.data.id
  // 主动触发校验
  // addFormRef.value.contractUrl=res.data.url
  addFormRef.value?.validateField('contractUrl')
  return res.data.url
  
}
// 删除合同文件
const removeUpload = () => {
  // 清空数据
  rentForm.value.contractUrl = ''
  rentForm.value.contractId = undefined
  // 触发校验
  addFormRef.value?.validateField('contractId')
}

// 点击确定添加合同
const  addRentConfirm=async()=>{
  try{
    // 校验表单
      await addFormRef.value?.validate()
      // 调用接口，提交数据
      await createRentAPI(rentForm.value)

      ElMessage.success('添加成功')
      dialogVisible.value=false
      // closeRent()

  }catch(err){

  }
}

// 二级表格展开触发
const onExpandChange=async(row:EnterpriseWithRent)=>{
  // console.log(row.id);
  const  res=await getRentListAPI(row.id)
  row.rentList=res.data
  // row.rentList = Array.isArray(res.data) ? res.data : [res.data];
}
// 退租合同
const outRent=(row:Datum)=>{
  ElMessageBox.confirm('您确定要退租吗', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async() => {
    await outRentAPI(row.id)
    row.status=3
    ElMessage.success('退租成功')
      })
     
}

// 删除合同弹窗、
const delRent= async(sonrow:Datum, fatherrow:EnterpriseWithRent)=>{
  ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async() => {
      // 删除合同（后端）
     await delRentAPI(sonrow.id)
    //  前端过滤掉删除的合同
    fatherrow.rentList=fatherrow.rentList.filter(item=>item.id!==sonrow.id)
      ElMessage.success('删除成功')

      })
     
}

// 续租合同
const renewRent=async(id:number)=>{
   dialogVisible.value=true
}


</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" link  @click="onSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" link @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 添加-表格区域 -->
   
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange"  row-key="id">
        <!-- 二级表格 -->
        <el-table-column type="expand">
  <template #default="{row}">
    <el-table :data="row.rentList">
      <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
      <el-table-column label="租赁起始时间" prop="startTime" />
      <el-table-column label="合同状态" prop="status">
                <!-- 合同的租赁状态 0待生效 1生效中 2已到期 3已退租 -->
                <template v-slot="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="{ row: sonrow }">
          <el-button  @click="renewRent(sonrow.id)" size="small" type="primary" link>续租</el-button>
          <el-button @click="outRent(sonrow)" size="small" type="primary" link :disabled="sonrow.status===3">退租</el-button>
          <el-button  @click="delRent(sonrow ,row)" size="small" type="primary" link :disabled="sonrow.status!==3">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </template>
</el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人"  prop="contact"/>
        <el-table-column label="联系电话"  prop="contactNumber" />
        <el-table-column label="操作"  width="280">
          <template #default="{ row }">
            <el-button size="small" type="primary" link  @click="addRent(row.id) "  >添加合同</el-button>
            <el-button size="small" type="primary" link @click="$router.push(`/exterpriseDetail/${row.id}`)">查看</el-button>
            <el-button size="small" type="primary" link @click="$router.push(`/exterpriseAdd/${row.id}`)" >编辑</el-button>
            <el-button size="small" type="primary" link  @click="delExterprise(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination :total="total" 
      layout="total, sizes prev, pager, next, jumper" 
       :page-sizes="[2,5,10,20,100]"
       v-model:page-size="params.pageSize"
       v-model:current-page="params.page"
       @change="getLiat()"
      />
     
      <!--添加合同弹窗                                                @close="closeRent"-->        
      <el-dialog title="添加合同  " width="600px"  v-model="dialogVisible"   @close="closeRent">
        <div class="form-container">
  <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
    <el-form-item label="租赁楼宇" prop="buildingId">
      <el-select v-model="rentForm.buildingId" placeholder="请选择">
        <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="租赁起止日期" prop="endTime">
      <el-date-picker 
        
      v-model="timeArr"
       type="daterange" range-separator="至" 
       start-placeholder="开始日期"
        end-placeholder="结束日期" 
        value-format="YYYY-MM-DD"
        :disabled-date="disabledDate" 
        />
    </el-form-item>
    <el-form-item label="租赁合同" prop="contractId">
      <el-upload accept=".doc, .pdf"  :http-request="onUploadRequest"  @remove="removeUpload"> 
        <el-button size="small" type="primary" link plain>上传合同文件</el-button>
        <template #tip>
          <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
        </template>
      </el-upload>
    </el-form-item>
  </el-form>
</div>
<!-- {{ timeArr }} -->
{{ rentForm }}
        <template #footer>
          
          <div class="dialog-footer">
             <el-button size="small" @click="closeRent ">取 消</el-button>
             <el-button size="small" type="primary" link @click="addRentConfirm" >确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.form-container{
  padding: 0px 80px;
  text-align: start;
}
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>